package me.seu.demo.service.netty.handler.event;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import me.seu.demo.service.netty.handler.Process;
import me.seu.demo.service.netty.message.GpsMessage;
import me.seu.demo.service.netty.utils.ByteUtils;
import me.seu.demo.service.netty.utils.CommUtils;
import me.seu.demo.service.netty.utils.NetUtils;

/**
 * LBS 报警包处理 0x19
 *
 * @author liangfeihu
 * @number 53669
 * @since 2021/4/7 下午5:23
 */
@Slf4j
public class AlertLbs implements Process {

    @Override
    public void execute(GpsMessage msg) throws Exception {
        byte[] packetContent = msg.getPacketContent();
        // 处理MCC、MNC、LAC、Cell ID
        handleMccAndCell(packetContent);
        // 设备信息、电压等级、GSM信号等级
        byte deviceInfo = packetContent[8];
        byte voltageLevel = packetContent[9];
        String voltageLevelDesc = CommUtils.getVoltageLevelDesc(voltageLevel);
        byte gsmLevel = packetContent[10];
        String gsmSignalLevelDesc = CommUtils.getGsmSignalLevelDesc(gsmLevel);
        log.info("[AlertGps]deviceInfo=0x{} voltageLevel={} gsmSignalLevel={}",
                ByteUtils.byteToHexString(deviceInfo), voltageLevelDesc, gsmSignalLevelDesc);
        // 报警语言详解
        byte alert = packetContent[11];
        String alertDesc = CommUtils.getAlertDesc(alert);
        byte language = packetContent[12];
        String languageDesc = CommUtils.getLanguageDesc(language);
        log.info("[AlertGps] alert={} language={}", alertDesc, languageDesc);

        // 返回响应包
        sedLbsReplyMsg(msg);
    }

    private void sedLbsReplyMsg(GpsMessage msg) {
        byte lbsReplyProtocol = (byte) 0x26;
        msg.setProtocolNo(lbsReplyProtocol);
        // 构造LBS报警响应包
        byte[] replyPacket = NetUtils.buildCommonReplyPacket(msg);

        ChannelHandlerContext ctx = msg.getCtx();
        if (ctx.channel().isWritable()) {
            // 将LBS报警响应包发送出去
            ctx.pipeline().writeAndFlush(Unpooled.wrappedBuffer(replyPacket));
        } else {
            ctx.pipeline().close();
        }
    }


    private void handleMccAndCell(byte[] packetContent) {
        byte[] mcc = new byte[]{packetContent[0], packetContent[1]};
        int mccNum = ByteUtils.byteArrayToInt(mcc, true);
        int mncNum = 0xFF & packetContent[2];
        byte[] lac = new byte[]{packetContent[3], packetContent[4]};
        int lacNum = ByteUtils.byteArrayToInt(lac, true);
        byte[] cell = new byte[]{0x00, packetContent[5], packetContent[6], packetContent[7]};
        int cellId = ByteUtils.byteArrayToInt(cell);
        log.info("[AlertLbs]mccNum:{} mncNum:{} lacNum:{} cellId:{}", mccNum, mncNum, lacNum, cellId);
    }

}
